package cn.wolfcode.web.controller;

import cn.wolfcode.domain.City;
import cn.wolfcode.domain.Province;
import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@Controller
public class JsonController {
    // 若存在 {"success":false,"msg":"用户名已注册"}
// 若不存在 {"success":true,"msg":"恭喜您登陆成功"}
    @RequestMapping("/checkUsername")
    @ResponseBody
    public JsonResult checkUsername(String username) {
        // 数据库查询, 模拟一下老王
        JsonResult jsonResult = new JsonResult();
        if ("老王".equals(username)) {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("用户名已注册");
        } else {
            jsonResult.setSuccess(true);
            jsonResult.setMsg("恭喜您登陆成功");
        }
        return jsonResult;
    }

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        //做判断
        JsonResult jsonResult = new JsonResult();
        if ("老王".equals(username) && "666".equals(password)) {
            jsonResult.setSuccess(true);
            jsonResult.setMsg("恭喜您登陆成功");
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("用户名或密码错误");
        }
        return jsonResult;
    }
//// 获取省份 JSON 数据
@RequestMapping("/provinces")
@ResponseBody
public List<Province> getProvinces(){
    List<Province> provinces = Province.getAllProvince();
    return provinces;

}
    // 获取对应省份的城市 JSON 数据
    @RequestMapping("/cities")
    @ResponseBody
    public List<City> getProvinces(Long pid){
        return City.getCityByProvinceId(pid);

    }


    @RequestMapping("/getTime")
    public void getTime(HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Date now = new Date();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(true);
        jsonResult.setMsg(now.toLocaleString());
        //java对象转成json对象
        writer.write(JSON.toJSONString(jsonResult));
        writer.flush();
    }

}
